package com.atguigu.spzx.manager.service.impl;
import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.manager.listener.ExcelListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.entity.system.Category;
import com.atguigu.spzx.model.entity.system.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
        @Autowired
        CategoryMapper categoryMapper;


    @Override
    public List<Category> findByParentId(Long parentId) {
       List<Category> List = categoryMapper.findByParentId(parentId);
        return List;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        //设置响应结果类型
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        //设置URlEndcode.endcode,防止中文乱码
        String filename = null;
        try {
            filename = URLEncoder.encode("分类数据", "utf-8");
            response.setHeader("Caontent-disporsition","attachement;filename=" + filename + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
            //查询数据中的数据
            List<Category> categories = categoryMapper.selectAll();
            List<CategoryExcelVo> categoryExcelVoslist = new ArrayList<>(categories.size());

            //写出数据到浏览器
            EasyExcel.write(response.getOutputStream(),CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVoslist);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    @Override
    public void importData(MultipartFile file) throws IOException {
        // 使用EasyExcel解析数据
        EasyExcel
        .read(file.getInputStream(),CategoryExcelVo.class,new ExcelListener(categoryMapper))
        .sheet("分类数据")
        .doRead();
    }
}
